<template>
    <div class="jd-login">
        <JdHeader title="登录" back></JdHeader>
        <van-form class="login-form" @submit="submitHandler">
            <van-cell-group inset>
                <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名', pattern: /\w{6,12}/ }]" />
                <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>
            <div class="register">
                还没有账号,<router-link to="./register">去注册</router-link>
            </div>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// 导入接口相关api
import { loginApi } from '@/api/users'

import { Toast } from 'vant'

import { useRouter, type Router } from 'vue-router'


const $router: Router = useRouter()

// 准备的数据
const username = ref<string>('')
const password = ref<string>('')

// 提交的表单事件
const submitHandler = async () => {
    // 发送请求
    const res = await loginApi(username.value, password.value)
    console.log(res);

    // 判断结果
    // 表示登录成功
    if (((res as unknown) as { code: string }).code === '200') {
        Toast({
            message: '登录成功',
            icon: 'phone-circle-o',
        })
        // 存储一下token和userId
        window.localStorage.setItem('token', res.data.token)
        window.localStorage.setItem('user_id', res.data.userid)

        // 跳转到首页路由
        setTimeout(() => {
            $router.push({ path: '/home' })
        }, 2000)

        return
    }

    // 代码执行到这里说明手机号不行
    Toast({
        message: '登录失败',
        icon: 'phone-circle-o',
    })
}
</script>
<style scoped lang="scss">
.jd-login {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .login-form {
        border: 1px solid #333;
        border-radius: 10px;
        .register{
            margin: 0 auto;
            width: 50%;
        }
    }
}
</style>